package neptune.manager.allocator;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Job {

	private int state;
	public static final int STATE_QUEUED = 0;
	public static final int STATE_RUNNING = 1;
	public static final int STATE_FINISH = 2;
	public static final int STATE_FAILED = 3;

	private String description;
	private long startTimestamp;
	private long finishTimestamp;

	private String id;
	private String taskId;

	public Job() {
		this.startTimestamp = 0;
		this.finishTimestamp = 0;
		this.state = Job.STATE_QUEUED;
	}

	public synchronized void setState(int state) {
		if (state == STATE_FINISH)
			this.finishTimestamp = System.currentTimeMillis();
		if (state == STATE_RUNNING)
			this.startTimestamp = System.currentTimeMillis();
		this.state = state;
	}

	public synchronized int getSate() {
		return state;
	}

	public synchronized String getStateDescription() {
		switch (this.state) {
		case STATE_FAILED:
			return "Failed";
		case STATE_FINISH:
			return "Finish";
		case STATE_QUEUED:
			return "Queued";
		case STATE_RUNNING:
			return "Running";
		default:
			return "Undefined";
		}
	}

	public synchronized String getDescription() {
		return description;
	}

	public synchronized void setDescription(String description) {
		this.description = description;
	}

	public synchronized String getId() {
		return id;
	}

	public synchronized void setId(String id) {
		this.id = id;
	}

	public synchronized String getTaskId() {
		return taskId;
	}

	public synchronized void setTaskId(String taskId) {
		this.taskId = taskId;
	}

	public synchronized String getElapsedTime() {
		long milliSeconds;
		switch (this.state) {
		case STATE_FAILED:
			return "--:--";
		case STATE_FINISH:
			milliSeconds = this.finishTimestamp - this.startTimestamp;
			return toMinuteFormat(milliSeconds);
		case STATE_QUEUED:
			return "--:--";
		case STATE_RUNNING:
			milliSeconds = System.currentTimeMillis() - this.startTimestamp;
			return toMinuteFormat(milliSeconds);
		default:
			return "Undefined";
		}
	}

	public boolean equals(Object otherObject) {
		// if (!super.equals(otherObject)) return false;
		Job otherJob = (Job) otherObject;
		String otherJobId = otherJob.getId();
		String otherTaskId = otherJob.getTaskId();
		if (otherJobId.equalsIgnoreCase(this.id)
				&& otherTaskId.equalsIgnoreCase(this.taskId)) {
			return true;
		} else {
			return false;
		}
	}

	private static String toMinuteFormat(long millisecond) {
		Date diff = new Date(millisecond);
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(diff);
		String secondi = String.valueOf(calendar.get(Calendar.SECOND));
		if (secondi.length() == 1)
			secondi = "0" + secondi;
		String minuti = String.valueOf(calendar.get(Calendar.MINUTE));
		if (minuti.length() == 1)
			minuti = "0" + minuti;
		return minuti + ":" + secondi;
	}
}
